package api

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"web_api_gogf/app/model"
	"web_api_gogf/app/service"
	"web_api_gogf/library/response"
)

var SysUser = SysUserApi{}

type SysUserApi struct {
}

//用户列表接口
func (s *SysUserApi) Index(r *ghttp.Request) {
	var searchParams *model.SysUserGetListReq
	if err := r.Parse(&searchParams); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	data, err := service.SysUser.GetPageList(searchParams)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	//角色列表
	var roleTreeList []*model.SysRoleTree
	//角色搜索参数
	var roleSearchParams model.SysRoleGetListReq
	roleList, err := service.SysRole.GetList(&roleSearchParams)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	//树结构转换原始数据
	roleTreeOriginList := ([]model.SysRoleTree)(nil)
	gconv.Structs(roleList, &roleTreeOriginList)
	//转换为树结构
	roleTreeList = service.SysRole.BuildTree(roleTreeOriginList)

	response.Json(r, 0, "加载成功", g.Map{
		"userList": data,
		"roleList": roleTreeList,
	})
}

// 保存用户数据
func (s *SysUserApi) Save(r *ghttp.Request) {
	var saveUserData *model.SysUserSaveReq
	if err := r.Parse(&saveUserData); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	err := service.SysUser.SaveUser(saveUserData)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "保存成功")
}

// 禁用用户
func (s *SysUserApi) Disable(r *ghttp.Request) {
	var userIds []uint
	recUserIds := r.Get("user_ids")
	userIds = gconv.SliceUint(recUserIds)
	if userIds == nil {
		response.JsonExit(r, 1, "请选择要禁用的用户")
	}
	err := service.SysUser.DisableUser(userIds)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "禁用成功")
}

//激活用户
func (s *SysUserApi) Enable(r *ghttp.Request) {
	var userIds []uint
	recUserIds := r.Get("user_ids")
	userIds = gconv.SliceUint(recUserIds)
	if userIds == nil {
		response.JsonExit(r, 1, "请选择要激活的用户")
	}
	err := service.SysUser.EnableUser(userIds)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "激活成功")
}
